use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::fs;


fn handle_client(mut stream: TcpStream) {
    println!("请求成功");
    // 获取客户端信息
    let mut buffer = [0; 512];
    stream.read(&mut buffer).unwrap();
    let request = String::from_utf8_lossy(&buffer[..]);
    println!("request:{}",&request);



    let get = b"GET / HTTP/1.1\r\n";
    let mut response;
    let mut  contents;
    if buffer.starts_with(get) {
        contents = fs::read_to_string("wwwroot/index.html").unwrap();
        response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents);
    } else {
        response = String::from("HTTP/1.1 404 NOT FOUND\r\n\r\n");
        contents = fs::read_to_string("wwwroot/404.html").unwrap();
    }
    // 发送响应
    let response = format!("{}{}", response, contents);
    stream.write(response.as_bytes()).unwrap();
    stream.flush().unwrap();
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("0.0.0.0:8000")?;

    // 接受连接并顺序处理
    for stream in listener.incoming() {
        handle_client(stream?);
    }
    Ok(())
}